package com.zhengshang.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.zhengshang.api.domain.AppBalanceRecord;
import com.zhengshang.api.domain.AppBillRecord;
import com.zhengshang.api.domain.AppBillRefundRecord;
import com.zhengshang.api.domain.AppPayRecord;
import com.zhengshang.api.mapper.AppBalanceRecordMapper;
import com.zhengshang.api.mapper.AppBillRecordMapper;
import com.zhengshang.api.mapper.AppBillRefundRecordMapper;
import com.zhengshang.api.mapper.AppPayRecordMapper;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.constant.app.PhoneBillConstants;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.pay.alipay.AlipayService;
import com.zhengshang.common.pay.wxpay.WxPayUtils;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.system.mapper.SysUserMapper;
//import fulu.sup.open.api.core.MethodConst;
//import fulu.sup.open.api.sdk.DefaultOpenApiClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("phoneBillTask")
public class PhoneBillTask
{
    protected final Logger logger = LoggerFactory.getLogger(PhoneBillTask.class);
    @Autowired
    private AppBillRecordMapper appBillRecordMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private AppBalanceRecordMapper appBalanceRecordMapper;
    @Autowired
    private AppPayRecordMapper appPayRecordMapper;
    @Autowired
    private AppBillRefundRecordMapper appBillRefundRecordMapper;
    @Autowired
    private AlipayService alipayService;

    public void autoRefresh()
    {
//
//        DefaultOpenApiClient client =  new DefaultOpenApiClient(PhoneBillConstants.GETWAY_HTTPS, PhoneBillConstants.APP_KEY, PhoneBillConstants.APP_SECRET, MethodConst.OPEN_API_ORDER_GET);
//
//        AppBillRecord appBillRecord = new AppBillRecord();
//        appBillRecord.setOrderState("1");
//        List<AppBillRecord> appBillRecordList = appBillRecordMapper.queryAppBillRecordList(appBillRecord);
//        for (AppBillRecord billRecord : appBillRecordList) {
//            JSONObject bizContent = new JSONObject();
//            bizContent.put("customer_order_no", billRecord.getOrderNum());
//            client.setBizContent(bizContent.toJSONString());
//            JSONObject jsonObject = JSONObject.parseObject(client.excute());
//            if (jsonObject.getIntValue("code") == 0) {
//                JSONObject resultObj = jsonObject.getJSONObject("result");
//                String orderState = resultObj.getString("order_state");
//                if ("success".equalsIgnoreCase(orderState)) {
//                    billRecord.setOrderState("3");
//                    billRecord.setFuluOrderId(resultObj.getString("order_id"));
//                    billRecord.setOperatorSerialNumber(resultObj.getString("operator_serial_number"));
//                } else if ("failed".equalsIgnoreCase(orderState)) {
//
//                    String state = "5";
//                    AppPayRecord appPayRecord = appPayRecordMapper.selectAppPayRecordById(billRecord.getPayId());
//                    String refundOrderNum = appPayRecord.getOrderNum() + "TK";
//                    String result = "";
//
//                    try {
//
//                        if ("1".equals(appPayRecord.getPayType())) {//支付宝退款
//                            result = alipayService.alipayRefund(appPayRecord.getOrderNum(), appPayRecord.getPayMoney().toString(), "话费充值失败退款", refundOrderNum);
//                            JSONObject object = JSONObject.parseObject(result);
//                            JSONObject alipayTradeRefundResponse = object.getJSONObject("alipay_trade_refund_response");
//                            if (!"10000".equals(alipayTradeRefundResponse.getString("code"))) {
//                                state = "6";
//                            }
//
//                        } else if ("2".equals(appPayRecord.getPayType())) {//微信退款
//                            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
////                            wxPayRefundRequest.setTransactionId(appPayRecord.getTransactionId());//微信支付订单号
//                            wxPayRefundRequest.setOutTradeNo(appPayRecord.getOrderNum());//商户订单号
//                            wxPayRefundRequest.setOutRefundNo(refundOrderNum);//商户退款单号
//                            int totalFee = appPayRecord.getPayMoney().multiply(new BigDecimal(100)).intValue();
//                            wxPayRefundRequest.setTotalFee(totalFee);//订单金额
//                            wxPayRefundRequest.setRefundFee(totalFee);//退款金额
//                            WxPayRefundResult wxPayRefundResult = WxPayUtils.getWxPayService().refund(wxPayRefundRequest);
//                            result = wxPayRefundResult.toString();
//
//                            logger.info("退款结果：" + wxPayRefundResult.toString());
//                        } else {
//                            continue;
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    //退款记录
//                    AppBillRefundRecord appBillRefundRecord = new AppBillRefundRecord();
//                    appBillRefundRecord.setUserId(billRecord.getUserId());
//                    appBillRefundRecord.setBillId(billRecord.getRecordId());
//                    appBillRefundRecord.setOrderNum(billRecord.getOrderNum());
//                    appBillRefundRecord.setRefundOrderNum(refundOrderNum);
//                    appBillRefundRecord.setRefundType(appPayRecord.getPayType());
//                    appBillRefundRecord.setRefundFee(appPayRecord.getPayMoney());
//                    appBillRefundRecord.setTotalFee(appPayRecord.getPayMoney());
//                    appBillRefundRecord.setResult(result);
//                    appBillRefundRecord.setCreateTime(DateUtils.getNowDate());
//                    appBillRefundRecord.setCreateBy("admin");
//                    appBillRefundRecordMapper.insertAppBillRefundRecord(appBillRefundRecord);
//
//                    billRecord.setOrderState(state);
//                }
//            } else if (jsonObject.getIntValue("code") == 3001) {
//                billRecord.setOrderState("2");
//            }
//            billRecord.setUpdateBy("admin");
//            billRecord.setUpdateTime(DateUtils.getNowDate());
//            appBillRecordMapper.updateAppBillRecord(billRecord);
//        }
//        logger.info("自动更新话费订单成功");
    }

    public void autoRefund(){
        AppBillRecord appBillRecordQuery = new AppBillRecord();
        appBillRecordQuery.setOrderState("2");
        List<AppBillRecord> appBillRecordList = appBillRecordMapper.queryAppBillRecordList(appBillRecordQuery);
        for (AppBillRecord billRecord : appBillRecordList) {
            String state = "5";
            AppPayRecord appPayRecord = appPayRecordMapper.selectAppPayRecordById(billRecord.getPayId());
            String result = "";
            AppBillRefundRecord appBillRefundRecordQuery = appBillRefundRecordMapper.selectByOrderNum(appPayRecord.getOrderNum());
            if (appBillRefundRecordQuery != null && appBillRefundRecordQuery.getRecordId() > 0l) {
                logger.info("订单<{}>已退款。", appBillRefundRecordQuery.getOrderNum());
                billRecord.setOrderState(state);
                billRecord.setUpdateBy("admin");
                billRecord.setUpdateTime(DateUtils.getNowDate());
                appBillRecordMapper.updateAppBillRecord(billRecord);
                continue;
            }
            String refundOrderNum = appPayRecord.getOrderNum() + "TK";

            try {

                if ("1".equals(appPayRecord.getPayType())) {//支付宝退款
                    result = alipayService.alipayRefund(appPayRecord.getOrderNum(), appPayRecord.getPayMoney().toString(), "话费充值失败退款", refundOrderNum);
                    JSONObject object = JSONObject.parseObject(result);
                    JSONObject alipayTradeRefundResponse = object.getJSONObject("alipay_trade_refund_response");
                    if (!"10000".equals(alipayTradeRefundResponse.getString("code"))) {
                        state = "6";
                    }

                } else if ("2".equals(appPayRecord.getPayType())) {//微信退款
                    WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
//                            wxPayRefundRequest.setTransactionId(appPayRecord.getTransactionId());//微信支付订单号
                    wxPayRefundRequest.setOutTradeNo(appPayRecord.getOrderNum());//商户订单号
                    wxPayRefundRequest.setOutRefundNo(refundOrderNum);//商户退款单号
                    int totalFee = appPayRecord.getPayMoney().multiply(new BigDecimal(100)).intValue();
                    wxPayRefundRequest.setTotalFee(totalFee);//订单金额
                    wxPayRefundRequest.setRefundFee(totalFee);//退款金额
                    WxPayRefundResult wxPayRefundResult = WxPayUtils.getWxPayService().refund(wxPayRefundRequest);
                    result = wxPayRefundResult.toString();

                    logger.info("退款结果：" + wxPayRefundResult.toString());
                } else {
                    continue;
                }

                //退款记录
                AppBillRefundRecord appBillRefundRecord = new AppBillRefundRecord();
                appBillRefundRecord.setUserId(billRecord.getUserId());
                appBillRefundRecord.setBillId(billRecord.getRecordId());
                appBillRefundRecord.setOrderNum(billRecord.getOrderNum());
                appBillRefundRecord.setRefundOrderNum(refundOrderNum);
                appBillRefundRecord.setRefundType(appPayRecord.getPayType());
                appBillRefundRecord.setRefundFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setTotalFee(appPayRecord.getPayMoney());
                appBillRefundRecord.setResult(result);
                appBillRefundRecord.setCreateTime(DateUtils.getNowDate());
                appBillRefundRecord.setCreateBy("admin");
                appBillRefundRecordMapper.insertAppBillRefundRecord(appBillRefundRecord);

                billRecord.setOrderState(state);
                billRecord.setUpdateBy("admin");
                billRecord.setUpdateTime(DateUtils.getNowDate());
                appBillRecordMapper.updateAppBillRecord(billRecord);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
